package org.example.SlApi.MctjApi;



import io.restassured.builder.RequestSpecBuilder;
import io.restassured.config.EncoderConfig;
import io.restassured.specification.RequestSpecification;
import org.apache.commons.codec.net.URLCodec;
import io.restassured.RestAssured;
import io.restassured.response.Response;
import org.example.JycInfo;

import org.example.utils.ReadConf;
import org.example.utils.TestDataLoader;


import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


import static org.example.RestClient.*;
import static org.example.utils.ConPlsqla.exec_select;


public class MctjApi {
    private static List<JycInfo> JycList = new ArrayList<>();
    private  static TestDataLoader testDataLoader;

    public static void main(String[] args) throws SQLException, UnsupportedEncodingException, ClassNotFoundException, IOException {
        // 直接在 main 方法中初始化 testDataLoader
        testDataLoader = new TestDataLoader();
        mctjApi();
    }
    public static int mctjApi() throws IOException, SQLException, ClassNotFoundException {//名称提交
        if (testDataLoader == null) {
            testDataLoader = new TestDataLoader();
        }

        // 登录并更新cookies
        loginAndUpdateCookies();

        Map<String, String> testData = testDataLoader.getTestData();
        String nameXzqh = testData.get("nameXzqh");
        String nameZh = testData.get("nameZh");
        String nameHy = testData.get("nameHy");
        String nameZzxs = testData.get("nameZzxs");
        String S_PROLOC = testData.get("S_PROLOC");
        String zyyw = testData.get("zyyw");
        //  nameZh + nameHy + "（" + nameXzqh + "）" + nameZzxs
//        String nameXzqh = "浙江";
//        String nameZh = "顶顶顶顶顶";
//        String nameHy = "建筑设计事务所";
//        String nameZzxs = "有限责任公司";
////        String nameQc = "S_PROLOC_PROVINCE_:330000_,S_PROLOC_CITY_:330100_,S_PROLOC_DISTRICT_:330102_,S_PROLOC_LOCATION_:330102001_,S_PROLOC_:浙江省杭州市上城区清波街道_,S_QYZTLX_:01_,S_REGCAP_:_,S_HYDL_:M_,S_HYZL_:7400_,S_HYXL_:7484_,S_GMLX_:0_,S_TRADPINY:AIDESHI_,S_ENTTRA_:非脚后跟_,S_QYLXDL_:11_,S_ENTTYPE_:1200_,S_ZCZJ_:_,S_RJCZE_:_,S_CZE_:_,S_SJQYENTNAME_:_,S_SJQYUNISCID_:_,S_COMMITLETTER_:1_,S_MCZZXS_:有限责任公司,S_OPSCOPE_:工程设计活动_,S_JYFWBYHAND_:工程设计活动_,S_MCHYSIGN_:1_,S_ISQZSP_:undefined_,S_NAMEREGION_:浙江_,S_NAMEINDUSTRY_:建筑设计事务所_,S_BZSM_:_,S_ISPCOM_:2_,S_GRPNAME_:_,S_ITE_:0_,S_ITENAME_:_,S_ITEREGNO_:_,S_ZZSIGN_:hz";
//        String S_PROLOC = "浙江省杭州市上城区清波街道";
////        String S_NAME = "";
//        String zyyw = "工程设计活动";
        URLCodec urlCodec = new URLCodec();
        String encodedParam = URLEncoder.encode(nameXzqh, "UTF-8");
        String encodedParam1 = URLEncoder.encode(nameZh, "UTF-8");
        String encodedParam2 = URLEncoder.encode(nameHy, "UTF-8");
        String encodedParam3 = URLEncoder.encode(nameZzxs, "UTF-8");
        String encodedParam5 = URLEncoder.encode(S_PROLOC, "UTF-8");
        String encodedParam7 = URLEncoder.encode(zyyw, "UTF-8");
        String formData = "ywtSldj.do?method=enterMczzws_zj&csrftoken=&nameZh=" + encodedParam1 + "&sbid=&sbms=1&znspsign=0&pripid=&name_id=&S_PROLOC_PROVINCE=330000&S_PROLOC_CITY=330100&S_PROLOC_DISTRICT=330102&S_PROLOC_STREET=330102001&S_PROLOC=" + encodedParam5 + "&S_QYZTLX=01&S_REGCAP=&S_MCZZXS=" + encodedParam3 + "&S_QYLXDL=11&S_ENTTYPE=1200&S_ZCZJ=&S_RJCZE=&S_CZE=&S_SJQYENTNAME=&S_SJQYUNISCID=&S_ZZSIGN=hz&S_GMLX=0&S_TRADPINY=AIDESHI&xzqhwz=0&S_HYDL=M&S_HYZL=7400&S_HYXL=7484&mcjbxx=S_PROLOC_PROVINCE_:330000_,S_PROLOC_CITY_:330100_,S_PROLOC_DISTRICT_:330102_,S_PROLOC_LOCATION_:330102001_,S_PROLOC_:" + encodedParam5 + "_,S_QYZTLX_:01_,S_REGCAP_:_,S_HYDL_:M_,S_HYZL_:7400_,S_HYXL_:7484_,S_GMLX_:0_,S_TRADPINY_:DINGDINGDINGDINGDING_,S_ENTTRA_:" + encodedParam1 + "_,S_QYLXDL_:11_,S_ENTTYPE_:1200_,S_ZCZJ_:_,S_RJCZE_:_,S_CZE_:_,S_SJQYENTNAME_:_,S_SJQYUNISCID_:_,S_COMMITLETTER_:1_,S_MCZZXS_:" + encodedParam3 + "_,S_OPSCOPE_:" + encodedParam7 + "_,S_JYFWBYHAND_:" + encodedParam7 + "_,S_MCHYSIGN_:1_,S_ISQZSP_:undefined_,S_NAMEREGION_:" + encodedParam + "_,S_NAMEINDUSTRY_:" + encodedParam2 + "_,S_BZSM_:_,S_ISPCOM_:2_,S_GRPNAME_:_,S_ITE_:0_,S_ITENAME_:_,S_ITEREGNO_:_,S_ZZSIGN_:hz&nameList=" + encodedParam + "," + encodedParam1 + "," + encodedParam2 + "," + encodedParam3 + "," + encodedParam1 + encodedParam2 + "（" + encodedParam + "）" + encodedParam3 + ";&basemcclsm=&clidsm=&ljmsign=2&ghcomboid=&ghopscope=&zrzysx=&gzqsign=&pri_pripid=&ispt=Y";
//        String encodedTextWithPercent = formData.replace("%", "%25");
//        System.out.println(encodedTextWithPercent);
        RequestSpecification requestSpec = new RequestSpecBuilder()
                .setContentType("multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW")
                .build();
        RestAssured.config = RestAssured.config().encoderConfig(
                EncoderConfig.encoderConfig().encodeContentTypeAs("multipart/form-data", io.restassured.http.ContentType.TEXT)
        );
        String Referer = ReadConf.getHost() + "ywtSldj.do?method=doMczzcc_zjsj&S_ITE=0";
        RestAssured.baseURI = ReadConf.getHost(); // 设置基础URI
        Response response = givenWithCookies()
                .spec(requestSpec)
                .when()
                .header("Referer", Referer)
               .log().all()
                .post(formData);


        List<String> cookies = response.getHeaders().getValues("Set-Cookie");
        int Code = response.getStatusCode();
        System.out.println(Code);
        if (Code == 302) {
            for (String cookie : cookies) {
                System.out.println("Set-Cookie Header: " + cookie);
            }
            String redirectUrl = response.getHeader("Location");
            System.out.println(redirectUrl);
            if (redirectUrl != null) {
                Response finalResponse = givenWithCookies()
                        .when()
                        .log().all()
                        .get(redirectUrl);
                int statusCode = finalResponse.getStatusCode();
                System.out.println("Status Code: " + statusCode);





                if(JycList.isEmpty()){
                    initJyclist();
                }

            }

            }



        return Code;

    }

    public static  List<JycInfo>  initJyclist() {
        List<JycInfo> jycInfoList = new ArrayList<>();
        Map<String, String> testData = testDataLoader.getTestData();
        String nameXzqh = testData.get("nameXzqh");
        String nameZh = testData.get("nameZh");
        String nameHy = testData.get("nameHy");
        String nameZzxs = testData.get("nameZzxs");

        String sql = "SELECT * FROM QCDZ_MC_SL_QYMCHZK WHERE entname LIKE ? and bhyjms IS NULL" ;
        String entname = nameZh + nameHy + "（" + nameXzqh + "）" + nameZzxs ;

        try (ResultSet rs = exec_select(sql, "%" + entname + "%")){

                while (rs != null && rs.next()) {
                    JycInfo jycInfo = new JycInfo();
                    jycInfo.setName_id(rs.getString("name_id"));// 替换为实际的字段名
                    jycInfo.setSbid(rs.getString("sbid"));
                    jycInfo.setEntname(rs.getString("entname"));
                    jycInfo.setQylxdl( rs.getString("qylxdl"));
                    jycInfo.setProloc( rs.getString("proloc"));

                    // 填充更多字段
                    jycInfoList.add(jycInfo);
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            for (JycInfo info : jycInfoList) {
                System.out.println("结果是"+info);
            }
            return jycInfoList;
    }


}





